package com.yuanss.backenddemo.exception;

import com.yuanss.backenddemo.common.HttpStatus;
import com.yuanss.backenddemo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author yuanss
 * @version 1.0
 * @description 自定义异常处理
 * @date 2024/6/9 18:44:29
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public R bizExceptionHandler(BizException e){
        log.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return R.error(e.getErrorCode(),e.getErrorMsg());
    }


    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseBody
    public R unauthorizedExceptionHandler(UnauthorizedException e){
        log.error("发生资源访问异常！原因是：{}",e.getMessage());
        return new R<>(HttpStatus.UNAUTHORIZED,"没有权限访问该资源",null);
    }

    /**
     * 处理其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception e){
        log.error("未知异常！原因是:",e);
        return R.error("系统未知异常");
    }
}
